<?php
/*
 Author: Gaurav Mishra <mishra.gaurav@siemens.com>
 SPDX-FileCopyrightText: © 2022 Siemens AG

 SPDX-License-Identifier: GPL-2.0-only
*/

/**
 * @namespace Fossology\DecisionImporter
 * @brief Namespace for Decision Importer agent
 */

namespace Fossology\DecisionImporter;

/**
 * @file
 * @brief Decision importer agent.
 */

define("DECISIONIMPORTER_AGENT_NAME", "decisionimporter");

use Exception;
use Fossology\Lib\Agent\Agent;

include_once(__DIR__ . "/version.php");
require_once "DecisionImporterIdFetcher.php";
require_once "FoDecisionData.php";
require_once "DecisionImporterDataCreator.php";

/**
 * @class DecisionImporterAgent
 * @brief Import decisions generated by Decision Exporter from JSON files
 */
class DecisionImporterAgent extends Agent
{
  /**
   * @var int $UPDATE_COUNT
   * How many rows to update at once to DB
   */
  public static $UPDATE_COUNT = 1000;

  const REPORT_KEY = "report";          ///< Key used to pass report name
  const LONG_OPT_KEYS = ["userselect"]; ///< Other CLI args required by agents

  /**
   * @var string $report
   * Location of JSON report.
   */
  private $report;

  /**
   * @var int $setUserId
   * User ID to use while creating decisions.
   */
  private $setUserId;

  /**
   * @var FoDecisionData $reportData
   * Object holding report data
   */
  private $reportData;

  /**
   * @var DecisionImporterIdFetcher $decisionImporterUtils
   * Fetcher object
   */
  private $decisionImporterUtils;

  /**
   * @var DecisionImporterDataCreator $decisionImporterDataCreator
   * Creator object
   */
  private $decisionImporterDataCreator;

  /**
   * @throws Exception
   */
  function __construct()
  {
    parent::__construct(DECISIONIMPORTER_AGENT_NAME, AGENT_VERSION, AGENT_REV);

    $this->agentSpecifLongOptions[] = self::REPORT_KEY . ':';
    foreach (self::LONG_OPT_KEYS as $opt) {
      $this->agentSpecifLongOptions[] = $opt . ":";
    }

    $dbManager = $this->container->get("db.manager");
    $pfileDao = $this->container->get("dao.pfile");
    $licenseDao = $this->container->get("dao.license");
    $agentDao = $this->container->get("dao.agent");
    $copyrightDao = $this->container->get("dao.copyright");
    $uploadDao = $this->container->get("dao.upload");
    $clearingDao = $this->container->get("dao.clearing");

    $this->decisionImporterUtils = new DecisionImporterIdFetcher($dbManager, $pfileDao, $licenseDao);
    $this->decisionImporterDataCreator = new DecisionImporterDataCreator($dbManager, $agentDao, $copyrightDao,
      $licenseDao, $uploadDao, $clearingDao);
  }

  /**
   * @copydoc Fossology::Lib::Agent::Agent::processUploadId()
   * @throws Exception Throws Exception if anything goes wrong.
   * @see Fossology::Lib::Agent::Agent::processUploadId()
   */
  function processUploadId($uploadId)
  {
    $userId = $this->userId;
    $groupId = $this->groupId;
    global $SysConf;
    $fileBase = $SysConf['FOSSOLOGY']['path'] . "/DecisionImport/";
    $this->processArgs();
    $this->report = $fileBase . $this->report;
    if (!file_exists($this->report) ||
      !is_readable($this->report)) {
      echo "No report to process\n";
      echo "Maybe the permissions on " . htmlspecialchars($fileBase) . " are not sufficient\n";
      return false;
    }

    $this->reportData = FoDecisionData::createFromFile($this->report);

    $this->heartbeat(0);

    $this->decisionImporterUtils->setUploadId($uploadId);
    $this->decisionImporterUtils->setGroupId($groupId);
    $this->decisionImporterUtils->setUserId($userId);

    $this->decisionImporterUtils->getOrCreateIds($this->reportData, $this);

    $this->decisionImporterDataCreator->setUserId($this->setUserId);
    $this->decisionImporterDataCreator->setGroupId($groupId);
    $this->decisionImporterDataCreator->setUploadId($uploadId);

    $this->decisionImporterDataCreator->createClearingDecisions($this->reportData, $this);
    $this->decisionImporterDataCreator->createMonkBulkData($this->reportData, $this);
    $this->decisionImporterDataCreator->createCopyrightData($this->reportData, $this, "copyright", $this->jobId);
    $this->decisionImporterDataCreator->createCopyrightData($this->reportData, $this, "ecc", $this->jobId);
    $this->decisionImporterDataCreator->createCopyrightData($this->reportData, $this, "ipra", $this->jobId);
    $this->decisionImporterDataCreator->createReportData($this->reportData);
    $this->decisionImporterDataCreator->createMainLicenses($this->reportData, $uploadId, $groupId);
    $this->heartbeat(0);

    return true;
  }

  /**
   * Process args and extract additional values.
   */
  private function processArgs(): void
  {
    $args = explode(" --", $this->args[self::REPORT_KEY]);
    $this->report = $args[0];
    $args = array_slice($args, 1);
    foreach ($args as $arg) {
      list($key, $value) = explode("=", $arg);
      if ($key == self::LONG_OPT_KEYS[0]) {
        $this->setUserId = intval($value);
      }
    }
  }
}
